//
//  YLCProgramAddViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/2/2.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCProgramAddViewController.h"
#import "YLCProgramAddView.h"
#import "YLCProgramAddCellModel.h"
#import "YLCFillMessageModel.h"
#import "YLCProgramTraitFillModel.h"
#import "HXPhotoModel.h"
#import "HXPhotoTools.h"
#import "YLCProgramSelectModel.h"
#import "SDWebImageManager.h"
#import "YLCProgramListViewController.h"

@interface YLCProgramAddViewController ()
@property (nonatomic ,strong)YLCProgramAddView *addView;
@end

@implementation YLCProgramAddViewController
{
    NSArray *cellArr;
    NSArray *photoList;
    NSArray *urlList;
    BOOL isFinish;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self createCustomView];
    [self bindViewModel];
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"提交" titleColor:RGB(255, 255, 255) selector:@selector(gotoInsert) target:self];
}
- (void)gotoInsert{
    YLCProgramAddCellModel *nameModel = cellArr[0];
    YLCProgramAddCellModel *traitModel = cellArr[2];
    YLCProgramAddCellModel *priceModel = cellArr[1];
    YLCProgramAddCellModel *inputmodel = cellArr[7];
    YLCProgramAddCellModel *starModel = cellArr[6];
    YLCProgramAddCellModel *periodModel = cellArr[4];
    YLCProgramAddCellModel *subsidyModel = cellArr[5];
    YLCProgramAddCellModel *personNumberModel = cellArr[3];
    YLCFillMessageModel *nameMessageModel = nameModel.cellModel;
    YLCFillMessageModel *traitMessageModel = traitModel.cellModel;
//    YLCProgramSelectModel *periodMessageModel = periodModel.cellModel;
    YLCFillMessageModel *periodMessageModel = periodModel.cellModel;
    YLCFillMessageModel *subsidyMessageModel = subsidyModel.cellModel;
    YLCFillMessageModel *personNumberMessageModel = personNumberModel.cellModel;
    
    NSArray *priceArr = priceModel.cellModel;
    NSMutableArray *goodPriceArr = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *goodNameArr = [NSMutableArray arrayWithCapacity:0];
    if (JK_IS_STR_NIL(nameMessageModel.message)) {
        [SVProgressHUD showErrorWithStatus:@"请输入项目名"];
        return;
    }
    if (JK_IS_STR_NIL(traitMessageModel.message)) {
        [SVProgressHUD showErrorWithStatus:@"请输入项目特点"];
        return;
    }
    for (YLCProgramTraitFillModel *model in priceArr) {
        if (JK_IS_STR_NIL(model.name)) {
            [SVProgressHUD showErrorWithStatus:@"请输入商品名称"];
            return;
        }
        [goodNameArr addObject:model.name];
        if (JK_IS_STR_NIL(model.price)) {
            [SVProgressHUD showErrorWithStatus:@"请输入商品价格"];
            return;
        }
        [goodPriceArr addObject:model.price];
    }
    if (JK_IS_STR_NIL(inputmodel.cellModel)) {
        [SVProgressHUD showErrorWithStatus:@"请输入项目介绍"];
        return;
    }

    if (JK_IS_STR_NIL(periodMessageModel.message)) {
//        [SVProgressHUD showErrorWithStatus:@"请选择保质期时间"];
//        return;
        periodMessageModel.message = @"";
    }
    if (JK_IS_STR_NIL(subsidyMessageModel.message)) {
        [SVProgressHUD showErrorWithStatus:@"请选择补贴金额"];
        return;
    }
    if (JK_IS_STR_NIL(personNumberMessageModel.message)) {
        [SVProgressHUD showErrorWithStatus:@"请填写人数"];
        return;
    }
    
//    if (JK_IS_ARRAY_NIL(photoList)) {
//        [SVProgressHUD showErrorWithStatus:@"请选择项目照片"];
//        return;
//    }

    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    NSMutableArray *photoBase = [NSMutableArray arrayWithCapacity:0];
    
    for (UIImage *photo in photoList) {
        
        NSString *photoString = [photo base64String];
        
        [photoBase addObject:[NSString stringWithFormat:@"data:image/jpeg;base64,%@",photoString]];
    }
    
    NSMutableArray *removeArray = [NSMutableArray array];
    for (NSDictionary *tempDic in urlList) {
        [removeArray addObject:tempDic[@"id"]];
    }
    
    NSDictionary *paramDict = @{};
    
//    if (JK_IS_STR_NIL(periodMessageModel.subString)||[periodMessageModel.subString isEqualToString:@"0"]) {
    if (JK_IS_STR_NIL(periodMessageModel.message)) {
        paramDict = @{@"userId":model.user_id,@"token":model.token,@"goodsName":nameMessageModel.message,@"classifyId":_classifyId,@"feature":traitMessageModel.message,@"subsidy":subsidyMessageModel.message,@"star":starModel.cellModel,@"description":inputmodel.cellModel,@"goodsId":JK_IS_STR_NIL(_goodsId)?@"":_goodsId,@"peopleNum":personNumberMessageModel.message};
    }else{
       paramDict =@{@"userId":model.user_id,@"token":model.token,@"goodsName":nameMessageModel.message,@"classifyId":_classifyId,@"feature":traitMessageModel.message,@"period":periodMessageModel.message,@"subsidy":subsidyMessageModel.message,@"star":starModel.cellModel,@"description":inputmodel.cellModel,@"goodsId":JK_IS_STR_NIL(_goodsId)?@"":_goodsId,@"peopleNum":personNumberMessageModel.message};
    }

    NSMutableDictionary *containerParam = paramDict.mutableCopy;
    
    for (int i = 0; i<goodPriceArr.count; i++) {
        NSString *price = goodPriceArr[i];
        
        [containerParam setObject:price forKey:[NSString stringWithFormat:@"prices[%d]",i]];
    }
    
    for (int i = 0; i<goodNameArr.count; i++) {
        NSString *priceName = goodNameArr[i];
        
        [containerParam setObject:priceName forKey:[NSString stringWithFormat:@"priceOptions[%d]",i]];
    }
    
    for (int i = 0; i<photoBase.count; i++) {
        NSString *photoString = photoBase[i];
        
        [containerParam setObject:photoString forKey:[NSString stringWithFormat:@"imgData[%d]",i]];
    }
    
    if (!JK_IS_ARRAY_NIL(removeArray)) {
        [containerParam setObject:removeArray forKey:@"removeImg"];
    }
    
    [YLCNetWorking loadNetServiceWithParam:containerParam.copy method:@"POST" urlPath:@"app/sygt/setGoods" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        if (_isEdit) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DetailLoad"];
        }
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];

        [self.navigationController popViewControllerAnimated:YES];
    }];
}
- (void)initDataSource{
    
    YLCProgramAddCellModel *nameModel = [[YLCProgramAddCellModel alloc] init];
    
    nameModel.cellType = YLCFiedCellType;
    
    YLCFillMessageModel *nameMessageModel = [[YLCFillMessageModel alloc] init];
    
    nameMessageModel.title = @"项目名称";
    
    nameMessageModel.placeholder = @"请输入项目名称";
    
    nameMessageModel.isRight = YES;
    
    nameMessageModel.message = _programModel.name;
    
    nameModel.cellModel = nameMessageModel;
    
    YLCProgramAddCellModel *traitModel = [[YLCProgramAddCellModel alloc] init];
    
    YLCFillMessageModel *traitMessageModel = [[YLCFillMessageModel alloc] init];
    
    traitMessageModel.placeholder = @"请输入项目特点";
    
    traitMessageModel.title = @"项目特点";
    
    traitMessageModel.isRight = YES;
    
    traitMessageModel.message = _programModel.feature;
    
    traitModel.cellModel = traitMessageModel;

    YLCProgramAddCellModel *priceModel = [[YLCProgramAddCellModel alloc] init];
    
    priceModel.cellModel = @[];
    
    priceModel.cellType = YLCCommondityCellType;
    
    if (!JK_IS_ARRAY_NIL(_programModel.options)) {
        NSMutableArray *priceContainer = [NSMutableArray arrayWithCapacity:0];
        
        for (NSDictionary *dict in _programModel.options) {
            YLCProgramTraitFillModel *model = [[YLCProgramTraitFillModel alloc] init];
            
            model.name = dict[@"goods_option"];
            
            model.price = dict[@"money"];
            
            [priceContainer addObject:model];
        }
        
        priceModel.cellModel = [priceContainer copy];
    }
    
    YLCProgramAddCellModel *inputmodel = [[YLCProgramAddCellModel alloc] init];
    
    inputmodel.cellType = YLCTextViewCellType;
    
    inputmodel.cellModel = _programModel.goodDescription;
    
    YLCProgramAddCellModel *starModel = [[YLCProgramAddCellModel alloc] init];
    
    starModel.cellType = YLCStarCellType;
    
    starModel.cellModel = @"1";
    
    if ([YLCFactory isStringOk:_programModel.star]) {
        starModel.cellModel = _programModel.star;
    }
    
    YLCProgramAddCellModel *photoAddModel = [[YLCProgramAddCellModel alloc] init];
    
    photoAddModel.cellType = YLCPhotoAddCellType;
    
//    YLCProgramAddCellModel *periodModel = [[YLCProgramAddCellModel alloc] init];
//
//    periodModel.cellType = YLCSelectCellType;
//
//    YLCProgramSelectModel *periodMessageModel = [[YLCProgramSelectModel alloc] init];
//
//    periodMessageModel.title = @"保质期";
//
//    periodMessageModel.placeholder = @"0";
//
//    periodMessageModel.titleColor = RGB(119, 123, 124);
//
//    periodMessageModel.textFont = 16.0;
//
//    periodMessageModel.selectList = @[@"0",@"1",@"2",@"3",@"6",@"12",@"24"];
//
//    periodMessageModel.subColor = [UIColor blackColor];
//
//    periodMessageModel.subString = _programModel.period;
//
//    periodModel.cellModel = periodMessageModel;
    
    
    YLCProgramAddCellModel *periodModel = [[YLCProgramAddCellModel alloc] init];
    
    periodModel.cellType = YLCFiedCellType;
    
    YLCFillMessageModel *periodMessageModel = [[YLCFillMessageModel alloc] init];

    periodMessageModel.title = @"保质期";
    
    periodMessageModel.placeholder = @"0";
    
    periodMessageModel.isRight = YES;
    
    periodMessageModel.isNumber = YES;
    
    periodMessageModel.isUnit = YES;
    
    periodMessageModel.unitStr = @"个月";
    
    periodMessageModel.message = _programModel.period;
    
    periodModel.cellModel = periodMessageModel;
    
    
    YLCProgramAddCellModel *subsidyModel = [[YLCProgramAddCellModel alloc] init];
    
    subsidyModel.cellType = YLCFiedCellType;
    
    YLCFillMessageModel *subsidyMessageModel = [[YLCFillMessageModel alloc] init];
    
    subsidyMessageModel.title = @"补贴";
    
    subsidyMessageModel.placeholder = @"补贴金额";
    
    subsidyMessageModel.isUnit = YES;

    subsidyMessageModel.unitStr = @"元";
    
    subsidyMessageModel.isRight = YES;
    
    subsidyMessageModel.isNumber = YES;
    
    subsidyMessageModel.message = _programModel.subsidy;
    
    subsidyModel.cellModel = subsidyMessageModel;
    
    YLCProgramAddCellModel *personNumberModel = [[YLCProgramAddCellModel alloc] init];
    
    personNumberModel.cellType = YLCFiedCellType;
    
    YLCFillMessageModel *personNumberMessageModel = [[YLCFillMessageModel alloc] init];
    
    personNumberMessageModel.title = @"填写人数";
    
    personNumberMessageModel.placeholder = @"0";
    
    personNumberMessageModel.isUnit = YES;

    personNumberMessageModel.unitStr = @"人";
    
    personNumberMessageModel.isRight = YES;
    
    personNumberMessageModel.isNumber = YES;
    
    personNumberMessageModel.message = _programModel.people_num;
    
    personNumberModel.cellModel = personNumberMessageModel;
    
    cellArr = @[nameModel,priceModel,traitModel,personNumberModel,periodModel,subsidyModel,starModel,inputmodel,photoAddModel];
    
//    NSMutableArray *webPhotoContainer = [NSMutableArray arrayWithCapacity:0];

//    if (!JK_IS_ARRAY_NIL(_programModel.caseList)) {
//        for (NSDictionary *urlDict in _programModel.caseList) {
//            [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlDict[@"case_img"]] options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//                isFinish = NO;
//            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//                isFinish = YES;
//                [webPhotoContainer addObject:image];
//                photoList = webPhotoContainer.copy;
//            }];
//        }
//    }

}
- (void)createCustomView{
    self.addView = [[YLCProgramAddView alloc] initWithFrame:CGRectMake(0, 0, self.view.frameWidth, self.view.frameHeight-64)];
    
    if (!JK_IS_ARRAY_NIL(_programModel.caseList)) {
        self.addView.insertPhotoList = _programModel.caseList;
    }
    
    [self.view addSubview:self.addView];
    
    [self reloadData];
}
- (void)reloadData{
    self.addView.cellArr = cellArr;
}
- (void)bindViewModel{
    @weakify(self);
    [self.addView.commodityDeleteSignal subscribeNext:^(id x) {
        @strongify(self);
        NSIndexPath *indexPath = x;
        [self deleteCommodityWithIndex:indexPath.row];
    }];
    
    [self.addView.commodityInsertSignal subscribeNext:^(id x) {
        @strongify(self);
        [self insertCommodity];
    }];
    
    [self.addView.programFieldChangeSignal subscribeNext:^(id x) {
        cellArr = x;
    }];
    
    [self.addView.changeReloadCellSignal subscribeNext:^(id x) {
        cellArr = x;
        [self reloadData];
    }];
    
    [self.addView.photoSignal subscribeNext:^(id x) {
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        
        if (JK_IS_ARRAY_NIL(x)) {
            photoList = @[];
        }
        for (HXPhotoModel *model in x) {
            [HXPhotoTools getHighQualityFormatPhoto:model.asset size:model.imageSize succeed:^(UIImage *image) {
                [array addObject:image];
                photoList = array.copy;
            } failed:^{
                [array addObject:model.thumbPhoto];//相机图片
                photoList = array.copy;
            }];
        }
        
    }];
    
    [self.addView.deletephotoSignal subscribeNext:^(id x) {
        urlList = [NSArray arrayWithArray:x];
    }];
}
- (void)insertCommodity{
    
    NSMutableArray *dataArr = [cellArr mutableCopy];
    
    YLCProgramAddCellModel *priceModel = dataArr[1];
    
    NSMutableArray *commodityArr = [(NSArray *)priceModel.cellModel mutableCopy];
    
    YLCProgramTraitFillModel *model = [[YLCProgramTraitFillModel alloc] init];
    
    model.name = @"";
    
    model.price = @"";
    
    [commodityArr addObject:model];
    
    priceModel.cellModel = commodityArr.copy;
    
    [dataArr setObject:priceModel atIndexedSubscript:1];
    
    cellArr = dataArr.copy;
    
    [self reloadData];
}
- (void)deleteCommodityWithIndex:(NSInteger)index{
    NSMutableArray *dataArr = [cellArr mutableCopy];
    
    YLCProgramAddCellModel *priceModel = dataArr[1];
    
    NSMutableArray *commodityArr = [(NSArray *)priceModel.cellModel mutableCopy];

    [commodityArr removeObjectAtIndex:index];
    
    priceModel.cellModel = commodityArr.copy;
    
    [dataArr setObject:priceModel atIndexedSubscript:1];
    
    cellArr = dataArr.copy;
    
    [self reloadData];
}
- (NSString *)title{
    return @"添加项目";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
